package cn.bugDance.domain.award.service.distribute.impl;

import cn.bugDance.domain.award.model.aggregate.GiveOutPrizesAggregate;
import cn.bugDance.domain.award.model.entity.DistributeAwardEntity;
import cn.bugDance.domain.award.model.entity.UserAwardRecordEntity;
import cn.bugDance.domain.award.model.entity.UserCreditAwardEntity;
import cn.bugDance.domain.award.model.valobj.UserAwardRecordStateVO;
import cn.bugDance.domain.award.repository.IAwardRepository;
import cn.bugDance.domain.award.service.distribute.IDistributeAward;
import cn.bugDance.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Random;

@Component("user_credit_random")
public class UserCreditRandom implements IDistributeAward {

    @Resource
    private IAwardRepository awardRepository;

    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAwardEntity) {
        String userId = distributeAwardEntity.getUserId();
        String awardConfig = distributeAwardEntity.getAwardConfig();
        String orderId = distributeAwardEntity.getOrderId();

        UserAwardRecordEntity userAwardRecordEntity = new UserAwardRecordEntity();
        userAwardRecordEntity.setAwardState(UserAwardRecordStateVO.COMPLETED);
        userAwardRecordEntity.setOrderId(orderId);

        String[] awardConfigs = awardConfig.split(Constants.SPLIT);
        Integer min = Integer.valueOf(awardConfigs[0]);
        Integer max = Integer.valueOf(awardConfigs[1]);
        Random random = new Random();

        // 生成min和max之间的随机数（包括min和max）
        int randomNumber = random.nextInt((max - min) + 1) + min;
        UserCreditAwardEntity userCreditAwardEntity = new UserCreditAwardEntity();
        userCreditAwardEntity.setUserId(userId);
        userCreditAwardEntity.setCreditAmount(randomNumber);

        GiveOutPrizesAggregate giveOutPrizesAggregate = new GiveOutPrizesAggregate();
        giveOutPrizesAggregate.setUserId(userId);
        giveOutPrizesAggregate.setUserCreditAwardEntity(userCreditAwardEntity);
        giveOutPrizesAggregate.setUserAwardRecordEntity(userAwardRecordEntity);

        awardRepository.giveOutPrizes(giveOutPrizesAggregate);
    }
}
